using System.Dynamic;
using Dapper;
using Eno.Domain.Entity.App;
using Eno.Domain.Repositories;
using Npgsql;

namespace Eno.Infrastructure.InfRepositories;

public class DepartmentRepository : IDepartmentRepository<AppDepartment>
{
    public readonly string _connectionString;

    public DepartmentRepository(string connectionString)
    {
        _connectionString = connectionString;
    }
    public async Task<dynamic> AdditionDepartmentAsync(AppDepartment entity)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"insert into app_department(""ID"",""DepartName"",""ParentID"",""IsActived"",""IsDeleted"",""CreatedAt"",""UpdatedAt"") values(@ID,@DepartName,@ParentID,@IsActived,@IsDeleted,@CreatedAt,@UpdatedAt)";
        var number = await conn.ExecuteAsync(sql, entity);
        return number;
    }

    public async Task<dynamic> DeleteDepartmentAsync(Guid DepartmentId)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"delete from app_department where ""ID""=@ID";
        var number = await conn.ExecuteAsync(sql, new { ID = DepartmentId });
        return number;
    }

    public async Task<dynamic> GetAppDepartmentByIdAsync(Guid DepartmentId)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"select * from app_department where ""ID""=@ID";
        var department = await conn.QueryFirstOrDefaultAsync<AppDepartment>(sql, new { ID = DepartmentId });
        if (department == null) return "没有该部门";
        return department;
    }

    public async Task<IEnumerable<AppDepartment>> GetAppDepartmentsAsync()
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"select * from app_department ";
        var departmentList = await conn.QueryAsync<AppDepartment>(sql);
        return departmentList;
    }

    public async Task<dynamic> UpdateDepartmentAsync(AppDepartment entity)
    {
        using var conn = new NpgsqlConnection(_connectionString);
        var sql = @"update app_department set ""DepartName""= @DepartName,""ParentID""= @ParentID,""UpdatedAt""=@UpdatedAt where ""ID""= @ID ";
        var number = await conn.ExecuteAsync(sql, entity);
        return number;
    }
}